package lab3;

import static org.junit.Assert.*;
import org.junit.Test;

/**
 * 版本1.0 算式类测试类 - 使用JUnit框架
 */
public class ArithmeticExpressionTest {

    /**
     * 测试加法运算
     */
    @Test
    public void testAddition() {
        ArithmeticExpression expr = new ArithmeticExpression(5.0, 3.0, '+');
        assertEquals(8.0, expr.getResult(), 0.001);
        assertEquals(5.0, expr.getOperand1(), 0.001);
        assertEquals(3.0, expr.getOperand2(), 0.001);
        assertEquals('+', expr.getOperator());
    }

    /**
     * 测试减法运算
     */
    @Test
    public void testSubtraction() {
        ArithmeticExpression expr = new ArithmeticExpression(10.0, 4.0, '-');
        assertEquals(6.0, expr.getResult(), 0.001);
    }

    /**
     * 测试乘法运算
     */
    @Test
    public void testMultiplication() {
        ArithmeticExpression expr = new ArithmeticExpression(6.0, 7.0, '*');
        assertEquals(42.0, expr.getResult(), 0.001);
    }

    /**
     * 测试除法运算
     */
    @Test
    public void testDivision() {
        ArithmeticExpression expr = new ArithmeticExpression(20.0, 5.0, '/');
        assertEquals(4.0, expr.getResult(), 0.001);
    }

    /**
     * 测试除数为零异常
     */
    @Test
    public void testDivisionByZero() {
        try {
            ArithmeticExpression expr = new ArithmeticExpression(10.0, 0.0, '/');
            fail("应该抛出ArithmeticException异常");
        } catch (ArithmeticException e) {
            // 预期的异常，测试通过
            assertTrue(e.getMessage().contains("除数不能为零"));
        }
    }

    /**
     * 测试无效运算符异常
     */
    @Test
    public void testInvalidOperator() {
        try {
            ArithmeticExpression expr = new ArithmeticExpression(5.0, 3.0, '%');
            fail("应该抛出IllegalArgumentException异常");
        } catch (IllegalArgumentException e) {
            // 预期的异常，测试通过
            assertTrue(e.getMessage().contains("无效的运算符"));
        }
    }

    /**
     * 测试负数运算
     */
    @Test
    public void testNegativeNumbers() {
        ArithmeticExpression expr1 = new ArithmeticExpression(-5.0, 3.0, '+');
        assertEquals(-2.0, expr1.getResult(), 0.001);
        
        ArithmeticExpression expr2 = new ArithmeticExpression(5.0, -3.0, '-');
        assertEquals(8.0, expr2.getResult(), 0.001);
    }

    /**
     * 测试小数运算
     */
    @Test
    public void testDecimalNumbers() {
        ArithmeticExpression expr = new ArithmeticExpression(2.5, 3.5, '+');
        assertEquals(6.0, expr.getResult(), 0.001);
    }

    /**
     * 测试toString方法
     */
    public void testToString() {
        ArithmeticExpression expr = new ArithmeticExpression(5.0, 3.0, '+');
        String expected = "5.00 + 3.00 = 8.00";
        String actual = expr.toString();
        assertEquals(expected, actual);
    }

    // JUnit测试类不需要main方法，通过JUnit运行器自动执行所有@Test注解的方法
}